import config from "@/projectConfig.js"

export default function fetch(options) {
  return new Promise((resolve, reject) => {
    let {
      url,
      data: reqParams,
      method = 'POST',
      isShowLoading = false
    } = options

    let token = uni.getStorageSync('token')
    let header = token ? {
      'Authorization': token
    } : {}
    try {
      // if (method.toUpperCase() == 'POST' || method.toUpperCase() == 'PUT') {
      //   header['content-type'] = 'application/x-www-form-urlencoded'
      // }
      // 显示加载
      if (isShowLoading) {
        uni.showLoading({
          title: '加载中'
        })
      }

      uni.request({
        url: `${config.baseUrl + url}`,
        header,
        method,
        data: reqParams,
        success(res) {
          if (isShowLoading) {
            uni.hideLoading()
          }
          let response = res.data

          resolve(response)
        },
        fail(err) {
          console.error(err)
          reject(err)
        }
      });
    } catch (error) {
      console.error("request err", error)
      if (isShowLoading) {
        uni.hideLoading()
      }
      if (error && (error.errMsg || error == 'TypeError: Failed to fetch')) {
        uni.showToast({
          title: '网络错误',
          icon: "none"
        })
      }
      reject(error)
    }
  })
}